package com.three.http;

import com.three.api.spi.common.ServiceDiscoveryFactory;
import com.three.api.srd.ServiceNames;
import com.three.api.srd.ServiceNode;
import com.three.tools.Utils;
import com.three.utils.JsonUtils;
import com.three.utils.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

import static com.three.api.srd.ServiceNames.ATTR_PUBLIC_IP;

/**
 * Created by mathua on 2017/6/13.
 */
@RestController
public class HttpServer {

    @RequestMapping("/getServerAddr")
    public String getServerAddr(@RequestParam(value = "openId", defaultValue = StringUtils.EMPTY) String openId) {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = attrs.getRequest().getSession();
        // 重复请求
        Long slat = (Long) session.getAttribute("salt");
        if (slat != null && System.currentTimeMillis() - slat <= 2 * 1000) {
            return JsonUtils.toJson(Response.build("required repeat!"));
        }
        List<ServiceNode> serviceNodes = ServiceDiscoveryFactory.create().lookup(ServiceNames.CONN_SERVER);
        session.setAttribute("salt", System.currentTimeMillis());
        session.setMaxInactiveInterval(10);
        if(!serviceNodes.isEmpty()) {
            for(ServiceNode serviceNode : serviceNodes) {
                if(serviceNode.getAttr(ATTR_PUBLIC_IP).equals(Utils.getZkServerIp())) {
                    return JsonUtils.toJson(Response.build(serviceNode.getHost(), serviceNode.getPort()));
                }
            }
        }
        return JsonUtils.toJson(Response.build("no server node!"));
    }
}
